import { Footer } from '@/components';
import {
  getLoginUserUsingGet,
  userLogoutUsingPost,
} from '@/services/openAPI-backend/userController';
import {
  HomeOutlined,
  LinkOutlined,
  LoginOutlined,
  ShoppingOutlined,TeamOutlined,
  UserOutlined, OpenAIOutlined, AlertOutlined,FormOutlined,
} from '@ant-design/icons';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { Link, history } from '@umijs/max';
import { FloatButton, Modal, message } from 'antd';
import defaultSettings from '../config/defaultSettings';
import '../public/font.css';
import { errorConfig } from './requestErrorConfig';
const { confirm } = Modal;
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
const centerPath = '/userControl/userCenter';
const marketPath = '/marketConfig/market';
const GPTPath = '/chatConsultant';
const forumPath = '/forumConfig/E-APIForum';
const teamPath = '/teamConfig/index';
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<InitialState> {
  //页面首次加载是，获取要全局保存的数据，比如用户登录信息
  const state: InitialState = {
    loginUser: undefined,
  };
  try {
    const res = await getLoginUserUsingGet();
    if (res.data) {
      state.loginUser = res.data;
      if (window.location.pathname === '/user/login') {
        message.info('您已经登陆了哦', [1]);
        history.push('/welcome');
      }
      if (window.location.pathname === '/user/register') {
        message.info('退出登录后才可以注册', [1]);
        history.push('/welcome');
      }
    }
  } catch (error) {
    if (location.pathname !== '/user/register' && location.pathname !=='/user/changepass') history.push(loginPath);
  }
  return state;
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const showLoginoutConfirm = () => {
    // @ts-ignore
    confirm({
      title: '是否要退出登录',
      content: '没保存的内容将会丢失',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      open: true,
      onOk() {
        handleSubmit();
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const PushtoCenter = () => {
    history.push(centerPath);
  };
  const PushtoGPT = () => {
    history.push(GPTPath);
  };
  const PushtoTeam = () => {
    history.push(teamPath);
  };
  const PushtoMarket = () => {
    history.push(marketPath);
  };
  const PushtoForum = () => {
    history.push(forumPath);
  };
  const handleSubmit = async () => {
    try {
      // 登录
      const res = await userLogoutUsingPost();
      if (res.data) {
        history.push('/user/login');
        return;
      }
    } catch (error) {
      message.error('发生错误');
    }
  };
  return {
    layout: 'top',
    actionsRender: () => [
      <>
        <FloatButton.Group
          trigger="hover"
          type="primary"
          tooltip={'快捷菜单'}
          style={{
            position: 'fixed',
            bottom: 24,
            right: 40,
          }}
          icon={<HomeOutlined />}
        >
          <FloatButton icon={<UserOutlined />} tooltip={'个人中心'} onClick={PushtoCenter} />
          <FloatButton icon={<ShoppingOutlined />} tooltip={'商城'} onClick={PushtoMarket} />
          <FloatButton
            icon={<LoginOutlined />}
            onClick={showLoginoutConfirm}
            tooltip={'退出登录'}
          />
        </FloatButton.Group>
      </>,
      <>
        <FloatButton.Group
            trigger="hover"
            type="primary"
            tooltip={'功能菜单'}
            style={{
              position: 'fixed',
              bottom: 24,
              right: 100,
            }}
            icon={<AlertOutlined />}
        >
          <FloatButton icon={<TeamOutlined />} tooltip={'E-API团队'} onClick={PushtoTeam}/>
          <FloatButton icon={<FormOutlined />} tooltip={'平台论坛'} onClick={PushtoForum} />
          <FloatButton icon={<OpenAIOutlined />} tooltip={'E-GPT'} onClick={PushtoGPT} />

        </FloatButton.Group>
      </>
    ],
    footerRender: () => <Footer />,
    onPageChange: () => {},
    bgLayoutImgList: [

    ],
    links: isDev
      ? [
          <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              style={{ minHeight: 280,minWidth: 600 }}
              disableUrlParams
              enableDarkTheme
              settings={defaultSettings}
              onSettingChange={(settings) => {
                // @ts-ignore
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
  credentials: 'include',
withCredentials: true,
};
